package com.wkcto.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wkcto.vo.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * 适用于前后端分离
 * spring security登录成功时执行的类
 * 成功时,返回的json
 */
@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {
    /**
     * 参数:
     * @param httpServletRequest 请求
     * @param httpServletResponse 应答
     * @param authentication spring security框架验证用户信息成功后的封装类。
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //登录的用户信息验证成功后执行的方法
//        PrintWriter writer = httpServletResponse.getWriter();
//        writer.println("{\"msg\":\"登录成功!\"}");
//        writer.flush();
//        writer.close();
        Result result = new Result();
        result.setCode(0);
        result.setError(1000);
        result.setMsg("登录成功!");


        OutputStream outputStream = httpServletResponse.getOutputStream();

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(outputStream, result);

        outputStream.flush();
    }
}
